package com.xiaotu.code.system;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jms.connection.CachingConnectionFactory;

/**
 * JMS连接工厂，防止过多的创建连接工厂.
 * 
 * @author chenxiangrong
 * 
 */
public class JmsConnectionFactoryContainer implements InitializingBean, DisposableBean {

	// 节点连接工厂容器
	private Map<String, CachingConnectionFactory> connectionFactoryContainer = new HashMap<String, CachingConnectionFactory>();
	// 当前节点的链接工厂
	private CachingConnectionFactory connectionFactory;

	public CachingConnectionFactory getConnectFactory(String url) {
		// 连接缓存工厂，如果是本节点则直接获取本节点连接工厂
		CachingConnectionFactory cacheFactory = null;
		// 获取连接工厂
		cacheFactory = connectionFactoryContainer.get(url);
		if (cacheFactory == null) {
			DefineActiveMQConnectionFactory factory = new DefineActiveMQConnectionFactory();
			factory.setBrokerURL(url);
			cacheFactory = new CachingConnectionFactory(factory);
			cacheFactory.setSessionCacheSize(10);
			connectionFactoryContainer.put(url, cacheFactory);
		}
		return cacheFactory;
	}

	@Override
	public void afterPropertiesSet() throws Exception {

		connectionFactoryContainer.put("tcp://127.0.0.1:61616", connectionFactory);
	}

	@Override
	public void destroy() throws Exception {
		// 关闭连接
		Iterator<String> iter = connectionFactoryContainer.keySet().iterator();
		while (iter.hasNext()) {
			connectionFactoryContainer.get(iter.next()).destroy();
		}
		connectionFactory.destroy();
	}

	public void setConnectionFactory(CachingConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public Map<String, CachingConnectionFactory> getConnectionFactoryContainer() {
		return connectionFactoryContainer;
	}

	public CachingConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}

}
